<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <!-- 导入页面的基本样式 -->
    <link rel="stylesheet" href="./css/search.css" />
    <!-- 导入 jQuery -->

</head>

<body>
    <div class="container">
        <!-- Logo -->
        <img src="./images/taobao_logo.png" alt="" class="logo" />

        <div class="box">
            <!-- tab 栏 -->
            <div class="tabs">
                <div class="tab-active">宝贝</div>
                <div>店铺</div>
            </div>
            <!-- 搜索区域（搜索框和搜索按钮） -->
            <div class="search-box">
                <input type="text" class="ipt" placeholder="请输入要搜索的内容" /><button class="btnSearch">
            搜索
          </button>
            </div>
            <div id="suggest-list"></div>
        </div>
    </div>
    <script src="./lib/jquery.js"></script>
    <script src="./lib/template-web.js"></script>
    <script type="type/html" id="list-tpl">
        {{each result}}
        <div id="suggest-item">{{$value[0]}}</div>
        {{/each}}
    </script>
    <script>
        $(function() {
            var kvObj = {};
            // 获取输入框内容
            var flag = false;
            $('.ipt').on('keyup', function() {
                if (flag) {
                    return
                }
                flag = true;
                var kv = $(this).val().trim();
                // 没有输入时返回
                if (kv.length <= 0) {
                    $("#suggest-list").fadeOut();
                    return
                }
                // console.log('+++++++++++++++++') 
                // 根据关键字发送请求
                var pkv = encodeURI(kv);
                if (kvObj[kv]) {
                    var list = template('list-tpl', kvObj[kv]);
                    $("#suggest-list").html(list).fadeIn();
                    return;
                }
                clearTimeout(timerId)
                var timerId = setTimeout(function() {
                    $.ajax({
                        url: 'https://suggest.taobao.com/sug?q=' + kv,
                        // 返回数据格式
                        dataType: 'jsonp',
                        success: function(res) {
                            if (res.result.length === 0) {
                                $("#suggest-list").empty().fadeOut();
                            }
                            console.log(res)
                                // 渲染数据
                            var list = template('list-tpl', res);
                            $("#suggest-list").html(list).fadeIn();
                            kvObj[kv] = res;
                            flag = false;
                        }
                    })
                }, 500)

            })


        })
    </script>
</body>

</html>